interface FetchOption{
    url:string;
    method?:'GET' | 'POST' | 'PUT' | 'DELETE';
    params?: Record<string, string | number>;
    data?: Record<string, any>;
}

export default function doFetch(option:FetchOption){
    option = option || {}
    let url = option.url
    let method:string = option.method||'GET'
    let params = option.params || {} // get参数
    let postData = option.data || {} // post参数

    method = method.toUpperCase();

    let paramsEntry = Object.entries(params)

    url = url.replace(/\?.*$/, '')
    
    if( paramsEntry.length > 0 ){
        url = url+'?'
        let arr = []
        for( let [k, v] of paramsEntry ){
            arr.push(k+'='+encodeURIComponent(v))
        }

        url = url + arr.join('&')
    }

    return new Promise((resolve, reject)=>{
        if( ['POST', 'PUT'].includes(method) ){
            fetch(url, {
                method: 'POST',
                headers:{
                    'Content-Type':'application/json'
                },
                body: JSON.stringify(postData)
            }).then(retData=>{
                return retData.json()
            }).then(resolve).catch(reject);
        }else{
            fetch(url).then(retData=>{
                return retData.json()
            }).then(resolve).catch(reject);
        }
    });
}

doFetch.get = (url:string, params={})=>{
    return doFetch({
        url,
        method:'GET',
        params
    })
}

doFetch.post = (url:string, data={}, params={})=>{
    return doFetch({
        url,
        method:'POST',
        data,
        params
    })
}